package com.vpx.server.controller.system;

import cn.hutool.core.collection.CollStreamUtil;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.io.FileUtil;
import cn.hutool.core.util.IdUtil;
import cn.hutool.core.util.ReUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSON;
import cn.hutool.json.JSONArray;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.vpx.dao.BaseDao;
import com.vpx.server.bean.entity.CProjectFlowInstance;
import com.vpx.server.bean.entity.CTypeRel;
import com.vpx.server.bean.order.base.BaseIdStrOrder;
import com.vpx.server.bean.order.system.*;
import com.vpx.server.bean.result.system.AttachUploadResult;
import com.vpx.server.bean.result.system.BaseInfoAttrResult;
import com.vpx.server.bean.result.system.ProjectFlowResult;
import com.vpx.server.bean.result.system.TemplateDetailListResult;
import com.vpx.server.framework.authority.AuthPoicy;
import com.vpx.server.framework.authority.RequestAuth;
import com.vpx.server.framework.base.ResultMsg;
import com.vpx.server.framework.exception.BizException;
import com.vpx.server.framework.utils.DateUtils;
import com.vpx.server.service.system.*;
import com.vpx.server.utils.BeanUtils;
import com.vpx.server.utils.UserLoginUtils;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import org.apache.commons.lang3.StringUtils;
import org.apache.ibatis.annotations.Param;
import org.apache.poi.util.StringUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.annotation.Id;
import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.net.URLEncoder;
import java.util.*;
import java.util.stream.Collectors;

import static cn.hutool.poi.excel.sax.ElementName.c;

@RestController
@RequestMapping(value = "/api/step")
@Api(tags = "流程步")
public class StepController {
    @Resource
    SqlService sqlService;
    @Resource
    SqlExtService sqlExtService;

    @Autowired
    private CProjectFlowInstanceService projectFlowInstanceService;

    @Autowired
    private CTypeRelService typeRelService;
    @Autowired
    private TemplateService templateService;

    @Autowired
    private BaseInfoService baseInfoService;
    @Autowired
    private XmlProjectService xmlProjectService;
    @Autowired
    private XmlHardConfigService xmlHardConfigService;
    @Autowired
    private XmlBusConfigService xmlBusConfigService;
    @Autowired
    private XmlObserverConfigService xmlObserverConfigService;
    @Autowired
    private XmlProtocolConfigService xmlProtocolConfigService;
    @Autowired
    private XmlShareConfigService xmlShareConfigService;
    @Autowired
    private XmlFlowConfigService xmlFlowConfigService;

    private final static String  BRANCH_TYPE_CODE = "0da30e7d08cb47bd9b22c01705b4df0e";
    private final static String  INSTANCE_TYPE_CODE = "3ed74995dccb4239adc56520e5c33c86";
    private final static String  BRANCH_TEMPLATE_ID = "1e2ac3227f7c2bc959138e0974f5dc94";
    private final static String  INSTANCE_TEMPLATE_ID = "254081f422f94978645111951a65e9f4";
    //保存分支用例构建数据
//    @PostMapping("/saveBranch")
//    @ApiOperation("保存分支用例构建数据")
//    public ResultMsg saveBranch(@RequestBody JSONObject param) {
//        String id = param.getStr("id");
//        //1、用例 2、分支3、流程
//        String type = param.getStr("type");
//        String content = param.getStr("content");
//        JSONArray children = param.getJSONArray("children");
//        if("2".equals(type)) {
//            saveBranch(id, type, content, children);
//        } else if("1".equals(type)) {
//            saveInstance(id, type, content, children);
//        } else if("3".equals(type)) {
//            saveFlow(id, type, content, children);
//        }
//
//
//
//        return ResultMsg.success();
//    }

    //    /**
//     * 处理分支信息
//     * @param id
//     * @param type
//     * @param content
//     * @param children
//     */
//    private void saveBranch(String id,String type,String content,JSONArray children) {
//        Map<String,Object> obj = new HashMap<>();
//        obj.put("id",id);
//        obj.put("content",content);
//        //c_project_flow_instance 更新测试用例表
//        sqlService.execute("3",obj);
//        //删除当前分支 下的所有数据  type(当前画布类型:1、用例2、分支3、流程)
//        this.sqlExtService.execute("delete from c_base_info_attr where base_info_id in (select bi.id from c_base_info bi where bi.type = '"+type+"' and bi.parent_all_id like '%"+id+"%')");
//        this.sqlExtService.execute("delete from c_base_info where  type = '"+type+"' and  parent_all_id like '%"+id+"%'");
//
//
//        //第一个节点为分支 不做处理
//
//
//        List<JSONObject> baseInfos = new ArrayList<>();
//        List<JSONObject> baseInfoAttrs = new ArrayList<>();
//        for(int i = 1;i < children.size();i ++) {
//            JSONObject node = children.getJSONObject(i);
//
//            JSONObject baseInfo = JSONUtil.createObj();
//            baseInfo.putByPath("id", node.getStr("nodeId"));
//            if(i == 1) {
//                //第一个节点的上级节点应该填写 分支对应ID
//                baseInfo.putByPath("parent_id", id);
//            } else {
//                baseInfo.putByPath("parent_id", node.getStr("parentNodeId"));
//            }
//            baseInfo.putByPath("type", type);
//            baseInfo.putByPath("node_type", node.getStr("type"));
//            baseInfo.putByPath("name", node.getStr("name"));
//            baseInfo.putByPath("branch_id", id);
//            baseInfo.putByPath("template_id", node.getStr("templateId"));
//            baseInfo.putByPath("type_code", node.getStr("typeId"));
//            baseInfo.putByPath("parent_all_id", id);
//            baseInfo.putByPath("num",IdUtil.getSnowflakeNextIdStr());
//            baseInfo.putByPath("create_user", UserLoginUtils.getCurrentUser() == null ? "admin" : UserLoginUtils.getCurrentUser().getId().toString());
//            baseInfo.putByPath("create_time", DateUtils.getDateTimeStr());
//            baseInfo.putByPath("node_method", node.getStr("nodeType"));
//            baseInfo.putByPath("notes", node.getStr("notes"));
//            baseInfos.add(baseInfo);
//            //构建属性
//            JSONArray nodeAttrs = node.getJSONArray("attrResultList");
//            for(int j = 0;j < nodeAttrs.size(); j++) {
//                JSONObject nodeAttr = nodeAttrs.getJSONObject(j);
//                JSONObject attr = JSONUtil.createObj();
//                attr.putByPath("id", IdUtil.getSnowflakeNextIdStr());
//                attr.putByPath("base_info_id", node.getStr("nodeId"));
//                attr.putByPath("template_id", node.getStr("templateId"));
//                attr.putByPath("template_attr_id", nodeAttr.getStr("id"));
//                attr.putByPath("type_code", node.getStr("typeId"));
//
//                attr.putByPath("attr_name", nodeAttr.getStr("attrName"));
//                attr.putByPath("attr_code", nodeAttr.getStr("attrCode"));
//                attr.putByPath("attr_type", nodeAttr.getStr("attrType"));
//                attr.putByPath("attr_content", nodeAttr.getStr("attrContent"));
//                attr.putByPath("attr_range", nodeAttr.getStr("attrRange"));
//                attr.putByPath("is_quote", nodeAttr.getStr("isQuote"));
//                attr.putByPath("is_get_set", nodeAttr.getStr("isGetSet"));
//                attr.putByPath("data_type", nodeAttr.getStr("dataType"));
//                attr.putByPath("protocol_type", nodeAttr.getStr("protocolType"));
//                attr.putByPath("sort_num", nodeAttr.getInt("sortNum"));
//                attr.putByPath("create_user", UserLoginUtils.getCurrentUser() == null ? "admin" : UserLoginUtils.getCurrentUser().getId().toString());
//                attr.putByPath("create_time", DateUtils.getDateTimeStr());
//
//                baseInfoAttrs.add(attr);
//            }
//        }
//        //批量保存数据
//        Map<String,Object> param = new HashMap<>();
//        param.put("list", baseInfos);
//        this.sqlService.execute("6", param);
//
//        param.put("list", baseInfoAttrs);
//        this.sqlService.execute("7", param);
//    }
//
//    /**
//     * 保存用例
//     * @param id
//     * @param type
//     * @param content
//     * @param children
//     */
//    private void saveInstance(String id,String type,String content,JSONArray children) {
//        Map<String,Object> obj = new HashMap<>();
//        obj.put("id",id);
//        obj.put("content",content);
//        //c_project_flow_instance 更新测试用例表
//        sqlService.execute("3",obj);
//
//    }
//
//
//
//    /**
//     * 保存流程
//     * @param id
//     * @param type
//     * @param content
//     * @param children
//     */
//    private void saveFlow(String id,String type,String content,JSONArray children) {
//        Map<String,Object> obj = new HashMap<>();
//        obj.put("id",id);
//        obj.put("content",content);
//        //c_project_flow_instance 更新测试用例表
//        sqlService.execute("3",obj);
//    }
    @PostMapping("/exportInfo")
    @ApiOperation("导出分支或用例")
    public ResultMsg exportInfo(@RequestBody JSONObject param ) {
        CProjectFlowInstance c = new CProjectFlowInstance();
        c.setInstanceName(param.getStr("instanceName"));
        c.setInstanceContent(param.getStr("instanceContent"));
        c.setBusType(param.getStr("busType"));
        c.setTypeCode(param.getStr("typeCode"));
        c.setId(IdUtil.getSnowflakeNextIdStr());
        Date date = DateUtil.date(System.currentTimeMillis());
        c.setCreateTime(date.toString());

        projectFlowInstanceService.insert(c);
        //保存分类关联数据
        CTypeRel obj = new CTypeRel();
        obj.setId(IdUtil.simpleUUID());
        obj.setCreateTime(date.toString());
        obj.setTransactionId(c.getId());
        obj.setTypeId(c.getTypeId());
        BaseInfoOrder order = new BaseInfoOrder();
        order.setId(c.getId());
        if("1".equals(c.getBusType())) {
            //分支
            obj.setCode("1");
            order.setType("2");
            order.setTemplateId(BRANCH_TEMPLATE_ID);
            order.setTypeCode(BRANCH_TYPE_CODE);
        } else {
            obj.setCode("2");
            order.setType("1");
            //用例模版
            order.setTemplateId(INSTANCE_TEMPLATE_ID);
            order.setTypeCode(INSTANCE_TYPE_CODE);
        }
        typeRelService.insert(obj);
        order.setName(c.getInstanceName());
        order.setIcon("kxgc");


        baseInfoService.saveBaseInfo(order);
        //用例或者分支 基础测试项属性表(c_base_info_attr)
        Map<String,Object> map = new HashMap<>();
        map.put("id",IdUtil.getSnowflakeNextIdStr());
        map.put("base_info_id",order.getId());
        map.put("template_id", order.getTemplateId());
        this.sqlService.execute("5" , map);
        return ResultMsg.success();
    }


    @GetMapping("/findInstanceOrBranchDetail")
    @ApiOperation("模板详情与属性列表查询")
    //@RequestAuth(poicy = AuthPoicy.AUTH)
    public ResultMsg<JSONObject> findInstanceOrBranchDetail(@RequestParam(required = false)  @ApiParam(value = "数据ID", name = "id") String id) {
        JSONObject jo =  this.sqlExtService.findOneObject("select * from c_project_flow_instance where id = '"+id+"'",JSONObject.class);
        String bus_type = jo.getStr("bus_type");
        if("1".equals(bus_type)) {
            //1分支2测试用例
            jo.putByPath("templateId",BRANCH_TEMPLATE_ID);
        } else if("2".equals(bus_type)) {
            jo.putByPath("templateId",INSTANCE_TEMPLATE_ID);
        }
        List<JSONObject> ja = this.sqlExtService.findListObject("select * from c_base_info_attr where base_info_id = '"+id+"'",JSONObject.class);
        jo.putByPath("attrResultList",ja);
        jo = BeanUtils.formatKey(jo,false);
        return ResultMsg.success(jo);
    }
    @GetMapping("/addBranchOrInstance")
    @ApiOperation("获取新增分支信息")
    //@RequestAuth(poicy = AuthPoicy.AUTH)
    public ResultMsg<JSONObject> addBranchOrInstance(@RequestParam(required = false)  @ApiParam(value = "1测试用例8分支", name = "typeCode") String typeCode) {
        JSONObject node  = JSONUtil.createObj();
        if("8".equals(typeCode)) {
            node.putByPath("template_icon","kxgc");
            node.putByPath("type_id","421cee7ddcc748cbb698b254236b97f6");
            node.putByPath("template_code","branch");
            node.putByPath("template_name","新增分支");
            node.putByPath("template_type","7");
            node.putByPath("id","1729152475171848192");
            node.putByPath("template_id", BRANCH_TEMPLATE_ID);
        } else if("1".equals(typeCode)){
            node.putByPath("template_icon","kxgc");
            node.putByPath("type_id","e7756ad8d0524394a502f64690181913");
            node.putByPath("template_code","branch");
            node.putByPath("template_name","新增用例");
            node.putByPath("template_type","1");
            node.putByPath("id","1729155019755421696");
            node.putByPath("template_id", INSTANCE_TEMPLATE_ID);
        }
        return ResultMsg.success(node);
    }


    @GetMapping("/findProjectConfig")
    @ApiOperation("下拉获取协议列表")
    //@RequestAuth(poicy = AuthPoicy.AUTH)
    public ResultMsg<List<JSONObject>> findProjectConfig(@RequestParam(required = false)  @ApiParam(value = "类别(1、硬件配置 2、总线配置 3、协议配置 4、共享配置 5、观察者配置 )", name = "configType") String configType) {
        List<JSONObject> ja = this.sqlExtService.findListObject("select config_code,config_name from c_project_config where config_type = '"+configType+"'",JSONObject.class);
        return ResultMsg.success(ja);
    }
    @PostMapping("/delInfo")
    @ApiOperation("用例或者流程的时候删除节点")
    public ResultMsg delInfo(@RequestBody JSONObject param) {
        String nodeId = param.getStr("nodeId");
        String branchOrInstanceId = param.getStr("branchOrInstanceId");//用例或者流程ID
        String content = param.getStr("content");
        this.updateContent(branchOrInstanceId, content);
        //删除分支或者用例下面的属性数据
        this.sqlExtService.execute("delete from c_base_info_attr where base_info_id in (select bi.id from c_base_info bi where  bi.parent_all_id like '%"+nodeId+"%' or bi.id ='"+nodeId+"')");
        this.sqlExtService.execute("delete from c_base_info where  parent_all_id like '%"+nodeId+"%' or id = '"+nodeId+"'");

        return ResultMsg.success();
    }

    @PostMapping("/addInfo")
    @ApiOperation("用例或者流程的时候新增节点")
    public ResultMsg addInfo(@RequestBody JSONObject param) {
        String type = param.getStr("type");//当前画布 type(当前画布类型:1、用例2、分支3、流程)
        String id = "";
        if("1".equals(type)) {
            //新增分支
            id = saveInstanchBranch(param);
        } else  if("3".equals(type)){
            //新增用例
            id = saveFlowInstanch(param);
        } else {
            // 新增流程步
            id = saveBranchStep(param);
        }
        //更新画布
        String branchOrInstanceId = param.getStr("branchOrInstanceId");//用例或者流程ID
        String content = param.getStr("content");
        this.updateContent(branchOrInstanceId, content);
        return ResultMsg.success(id);
    }
    private String saveBranchStep(JSONObject param) {
        String nodeId = param.getStr("nodeId");
        String toolId = param.getStr("toolId"); //当前拖拽的工具箱中的工具ID
        String type = param.getStr("type");//当前画布 type(当前画布类型:1、用例2、分支3、流程)
        String branchOrInstanceId = param.getStr("branchOrInstanceId");//用例或者流程ID 或者分支ID
        JSONObject info = this.sqlExtService.findOneObject("select * from c_template where id = '"+toolId+"'", JSONObject.class);

        JSONObject baseInfo = JSONUtil.createObj();
        baseInfo.putByPath("id",nodeId);
        baseInfo.putByPath("type", "2");
        baseInfo.putByPath("node_type", "2");
        baseInfo.putByPath("name", info.getStr("template_name"));
        baseInfo.putByPath("branch_id", branchOrInstanceId);
        baseInfo.putByPath("template_id", info.getStr("id"));
        baseInfo.putByPath("type_code", info.getStr("type_id"));
        baseInfo.putByPath("parent_all_id", branchOrInstanceId);
        baseInfo.putByPath("num", IdUtil.getSnowflakeNextIdStr());
        baseInfo.putByPath("node_method", "2");
        baseInfo.putByPath("notes", "false");
        baseInfo.putByPath("create_user", UserLoginUtils.getCurrentUser() == null ? "admin" : UserLoginUtils.getCurrentUser().getId().toString());
        baseInfo.putByPath("create_time", DateUtils.getDateTimeStr());

        List<JSONObject> attrs = this.sqlExtService.findListObject("select * from c_template_attr where template_id = '"+toolId+"'",JSONObject.class);
        List<JSONObject> baseInfos = new ArrayList<>();
        List<JSONObject> baseInfoAttrs = new ArrayList<>();
        for(int i = 0; i < attrs.size(); i++) {
            JSONObject attr = attrs.get(i);
            String template_attr_id = attr.getStr("id");
            attr.putByPath("id",IdUtil.getSnowflakeNextIdStr());
            attr.putByPath("base_info_id", nodeId);
            attr.putByPath("template_id", baseInfo.getStr("template_id"));
            attr.putByPath("template_attr_id", template_attr_id);
            attr.putByPath("type_code", baseInfo.getStr("type_code"));

            attr.putByPath("create_user", UserLoginUtils.getCurrentUser() == null ? "admin" : UserLoginUtils.getCurrentUser().getId().toString());
            attr.putByPath("create_time", DateUtils.getDateTimeStr());

            replateBaseInfoAttr(attr);
            baseInfoAttrs.add(attr);
        }
        baseInfos.add(baseInfo);
        //批量保存数据
        Map<String,Object> paramMap = new HashMap<>();
        paramMap.put("list", baseInfos);
        this.sqlService.execute("6", paramMap);
        paramMap.put("list", baseInfoAttrs);
        this.sqlService.execute("7", paramMap);
        return nodeId;
    }

    /**
     * 保存用例分支
     * @param param
     */
    private String  saveInstanchBranch(JSONObject param) {

        String toolId = param.getStr("toolId"); //当前拖拽的工具箱中的工具ID
        String type = param.getStr("type");//当前画布 type(当前画布类型:1、用例2、分支3、流程)
        String branchOrInstanceId = param.getStr("branchOrInstanceId");//用例ID
        String nodeId = param.getStr("nodeId");
        List<JSONObject> branchs = null;
        List<JSONObject> branchAtts = null;
        if(StringUtils.isNotBlank(toolId)) {
            branchs = this.sqlExtService.findListObject("select * from c_base_info where type = '2' and (id  = '"+toolId+"' or branch_id = '"+toolId+"')",JSONObject.class);

            branchAtts = this.sqlExtService.findListObject("select a.* from c_base_info_attr a where a.base_info_id in (" +
                    "select c.id from c_base_info c where c.type = '2' and (c.id  = '"+toolId+"' or c.branch_id = '"+toolId+"')" +
                    ")",JSONObject.class);
        } else {
            toolId = param.getStr("oldId");
            branchs = this.sqlExtService.findListObject("select * from c_base_info where  (id  = '"+toolId+"' or branch_id = '"+toolId+"')",JSONObject.class);

            branchAtts = this.sqlExtService.findListObject("select a.* from c_base_info_attr a where a.base_info_id in (" +
                    "select c.id from c_base_info c where  (c.id  = '"+toolId+"' or c.branch_id = '"+toolId+"')" +
                    ")",JSONObject.class);
        }

        List<JSONObject> baseInfos = new ArrayList<>();
        List<JSONObject> baseInfoAttrs = new ArrayList<>();
        Map<String,String> idMap = new HashMap<>();
        for(int i = 0;i < branchs.size();i ++) {
            //旧ID 与新ID 映射
            JSONObject obj = branchs.get(i);
            String oldId = obj.getStr("id");
            String newId = IdUtil.getSnowflakeNextIdStr();
            String node_type = obj.getStr("node_type");//当前节点类型node_type(1测试用例2流程步8分支)
            if("1".equals(type) &&  "8".equals(node_type)) {
                //1、用例 的分支
                newId = nodeId;
            }
            idMap.put(oldId, newId);
        }
        for(int i = 0;i < branchs.size();i ++) {
            JSONObject obj = branchs.get(i);
            String node_type = obj.getStr("node_type");//当前节点类型node_type(1测试用例2流程步8分支)
            obj.putByPath("id", idMap.get(obj.getStr("id")));
            obj.putByPath("type", type);
            obj.putByPath("instance_id", branchOrInstanceId);
            obj.putByPath("branch_id", idMap.get(obj.getStr("branch_id")));
            if("1".equals(type) &&  "8".equals(node_type)) {
                //1、用例 的分支
                obj.putByPath("parent_id", branchOrInstanceId);
                obj.putByPath("parent_all_id", nodeId + "|" + branchOrInstanceId);
            } else {
                obj.putByPath("parent_id", idMap.get(obj.getStr("parent_id")));
                obj.putByPath("parent_all_id", obj.getStr("branch_id") + "|" + branchOrInstanceId);
            }


            obj.putByPath("num", IdUtil.getSnowflakeNextIdStr());
            obj.putByPath("node_method", "2");
            obj.putByPath("notes", "false");
            obj.putByPath("create_user", UserLoginUtils.getCurrentUser() == null ? "admin" : UserLoginUtils.getCurrentUser().getId().toString());
            obj.putByPath("create_time", DateUtils.getDateTimeStr());
            baseInfos.add(obj);
        }

        for(int i = 0;i < branchAtts.size();i ++) {
            JSONObject obj = branchAtts.get(i);
            obj.putByPath("id", IdUtil.getSnowflakeNextIdStr());
            obj.putByPath("base_info_id", idMap.get(obj.getStr("base_info_id")));
            obj.putByPath("create_user", UserLoginUtils.getCurrentUser() == null ? "admin" : UserLoginUtils.getCurrentUser().getId().toString());
            obj.putByPath("create_time", DateUtils.getDateTimeStr());
            replateBaseInfoAttr(obj, idMap);
            baseInfoAttrs.add(obj);
        }

        //批量保存数据
        Map<String,Object> paramMap = new HashMap<>();
        paramMap.put("list", baseInfos);
        this.sqlService.execute("6", paramMap);

        paramMap.put("list", baseInfoAttrs);
        this.sqlService.execute("7", paramMap);

        return nodeId;
    }
    private void replateBaseInfoAttr(JSONObject obj) {
        String protocol_type = obj.getStr("protocol_type", "");
        //一般协议为空
        if(StringUtils.isBlank(protocol_type)) {
            //判断当前内容是否引用
            String attr_content = obj.getStr("attr_content","");
            if(match(attr_content)) {
                attr_content = attr_content.substring(0, StrUtil.ordinalIndexOf(attr_content, "#", 2) + 1) +
                        obj.getStr("base_info_id") +
                        attr_content.substring(StrUtil.ordinalIndexOf(attr_content, "#", 3), attr_content.length());
            }
            obj.putByPath("attr_content", attr_content);
        }
    }
    private void replateBaseInfoAttr(JSONObject obj, Map<String,String> idMap) {
        String protocol_type = obj.getStr("protocol_type", "");
        //一般协议为空
        if(StringUtils.isBlank(protocol_type)) {
            //判断当前内容是否引用
            String attr_content = obj.getStr("attr_content","");
            if(match(attr_content)) {
                String oldId = attr_content.substring(StrUtil.ordinalIndexOf(attr_content, "#", 2) + 1,  StrUtil.ordinalIndexOf(attr_content, "#", 3));
                String newId = idMap.get(oldId);
                attr_content = attr_content.substring(0, StrUtil.ordinalIndexOf(attr_content, "#", 2) + 1) +
                        newId +
                        attr_content.substring(StrUtil.ordinalIndexOf(attr_content, "#", 3), attr_content.length());
            }
            obj.putByPath("attr_content", attr_content);
        }
    }
    private boolean match(String content) {
        String regex  ="#.+#.+#.+#.+#";
        return ReUtil.isMatch(regex, content);
    }
    private String saveFlowInstanch(JSONObject param) {
        String toolId = param.getStr("toolId"); //当前拖拽的工具箱中的工具ID
        String type = param.getStr("type");//当前画布 type(当前画布类型:1、用例2、分支3、流程)
        //流程ID
        String branchOrInstanceId = param.getStr("branchOrInstanceId");
        //测试用例ID
        String nodeId = param.getStr("nodeId");

        String projectId = param.getStr("projectId");

        List<JSONObject> branchs = this.sqlExtService.findListObject("select * from c_base_info where type = '1' and (id  = '"+toolId+"' or instance_id = '"+toolId+"')",JSONObject.class);

        List<JSONObject> branchAtts = this.sqlExtService.findListObject("select a.* from c_base_info_attr a where a.base_info_id in (" +
                "select c.id from c_base_info c where c.type = '1' and (c.id  = '"+toolId+"' or c.instance_id = '"+toolId+"')" +
                ")",JSONObject.class);
        List<JSONObject> baseInfos = new ArrayList<>();
        List<JSONObject> baseInfoAttrs = new ArrayList<>();
        Map<String,String> idMap = new HashMap<>();
        for(int i = 0;i < branchs.size();i ++) {
            //旧ID 与新ID 映射
            JSONObject obj = branchs.get(i);
            String oldId = obj.getStr("id");
            String newId = IdUtil.getSnowflakeNextIdStr();
            String node_type = obj.getStr("node_type");//当前节点类型node_type(1测试用例2流程步8分支)
            if("3".equals(type) &&  "1".equals(node_type)) {
                //3、流程 的分支
                newId = nodeId;
            }
            idMap.put(oldId, newId);
        }
        String id = "";
        for(int i = 0;i < branchs.size();i ++) {
            JSONObject obj = branchs.get(i);
            String node_type = obj.getStr("node_type");//当前节点类型node_type(1测试用例2流程步8分支)
            obj.putByPath("id", idMap.get(obj.getStr("id")));
            obj.putByPath("type", type);
            obj.putByPath("flowinstance_id", branchOrInstanceId);
            obj.putByPath("instance_id", idMap.get(obj.getStr("instance_id")));

            obj.putByPath("branch_id", idMap.get(obj.getStr("branch_id")));

            if("3".equals(type) &&  "1".equals(node_type)) {
                obj.putByPath("parent_id", branchOrInstanceId);
                id = obj.getStr("id");
                obj.putByPath("parent_all_id", obj.getStr("id") + "|"  +  branchOrInstanceId);
                if("1".equals(node_type)) {
                    obj.putByPath("source_id", toolId);
                }
            } else {
                obj.putByPath("parent_id", idMap.get(obj.getStr("parent_id")));
                if("8".equals(node_type)) {
                    //分支
                    obj.putByPath("parent_all_id", obj.getStr("id") + "|" + obj.getStr("instance_id") + "|" +  branchOrInstanceId);
                } else {
                    obj.putByPath("parent_all_id", obj.getStr("branch_id") + "|" + obj.getStr("instance_id") + "|" +  branchOrInstanceId);
                }
            }
            obj.putByPath("num", IdUtil.getSnowflakeNextIdStr());
            obj.putByPath("node_method", "2");
            obj.putByPath("notes", "false");
            obj.putByPath("create_user", UserLoginUtils.getCurrentUser() == null ? "admin" : UserLoginUtils.getCurrentUser().getId().toString());
            obj.putByPath("create_time", DateUtils.getDateTimeStr());
            obj.putByPath("project_id", projectId);
            baseInfos.add(obj);
        }
        for(int i = 0;i < branchAtts.size();  i ++) {
            JSONObject obj = branchAtts.get(i);
            obj.putByPath("id", IdUtil.getSnowflakeNextIdStr());
            obj.putByPath("base_info_id", idMap.get(obj.getStr("base_info_id")));
            obj.putByPath("create_user", UserLoginUtils.getCurrentUser() == null ? "admin" : UserLoginUtils.getCurrentUser().getId().toString());
            obj.putByPath("create_time", DateUtils.getDateTimeStr());
            replateBaseInfoAttr(obj, idMap);
            baseInfoAttrs.add(obj);
        }

        //批量保存数据
        Map<String,Object> paramMap = new HashMap<>();
        paramMap.put("list", baseInfos);
        //保存base_info数据
        this.sqlService.execute("13", paramMap);
        paramMap.put("list", baseInfoAttrs);
        this.sqlService.execute("7", paramMap);
        return id;
    }


    @GetMapping("/getBaseInfoAttr")
    @ApiOperation("获取节点属性")
    public ResultMsg getBaseInfoAttr(@RequestParam(required = false)  @ApiParam(value = "基础信息节点", name = "id") String id) {
        List<JSONObject> list = this.sqlExtService.findListObject("select * from c_base_info_attr where base_info_id = '"+id+"' order by sort_num asc",JSONObject.class);
        return ResultMsg.success(list);
    }
    @PostMapping("/saveBaseInfoAttr")
    @ApiOperation("保存节点属性")
    public ResultMsg saveBaseInfoAttr(@RequestBody JSONArray params) {
        //批量保存数据
        Map<String,Object> paramMap = new HashMap<>();
        paramMap.put("list", params);
        this.sqlService.execute("7", paramMap);
        String name = "";
        String baseInfoId = "";
        for(int i = 0; i < params.size(); i++) {
            if("Describe".equals(params.getJSONObject(i).getStr("attr_code"))); {
                name = params.getJSONObject(i).getStr("attr_content");
                baseInfoId = params.getJSONObject(i).getStr("base_info_id");
                break;
            }
        }
        if(StringUtils.isNotBlank(name) && StringUtils.isNotBlank(baseInfoId)) {
            this.sqlExtService.execute("update c_base_info set name = '"+name+"' where id = '"+baseInfoId+"'");
        }
        return ResultMsg.success();
    }
    @PostMapping("/changNotes")
    @ApiOperation("注释与反注释")
    public ResultMsg changNotes(@RequestBody JSONObject param) {
        //批量保存数据
        String id = param.getStr("nodeId");
        String notes = param.getStr("notes");
        this.sqlExtService.execute("update c_base_info set notes = '"+notes+"' where parent_all_id like '%"+id+"%'");

        String branchOrInstanceId = param.getStr("branchOrInstanceId");//用例或者流程ID
        String content = param.getStr("content");
        this.updateContent(branchOrInstanceId, content);
        return ResultMsg.success();
    }

    @GetMapping("/findChildren")
    @ApiOperation("获取子级")
    public ResultMsg findChildren(@RequestParam(required = false)  @ApiParam(value = "节点ID", name = "nodeId") String nodeId,
                                  @RequestParam(required = false)  @ApiParam(value = "当前画布 type(当前画布类型:1、用例2、分支3、流程)", name = "type") String type) {
        List<JSONObject> list = this.sqlExtService.findListObject("select * from c_base_info where parent_all_id like '%"+nodeId+"%' order by num desc",JSONObject.class);
        if("1".equals(type)) {
            //点击分支 获取分支下的的节点
            list = sortStep(list,nodeId);
            return ResultMsg.success(list);
        } else {
            //当前画布为流程的时候 查询用例下面的分支 及 分支对应的流程步
            List<JSONObject> branchs = new ArrayList<>();
            Map<String,List<JSONObject>> stepMap = new HashMap<>();
            for(int i = 0;i < list.size(); i++) {
                JSONObject obj = list.get(i);
                JSONObject node = JSONUtil.createObj();
                node.putByPath("id", obj.getStr("id"));
                node.putByPath("name", obj.getStr("name"));
                node.putByPath("node_type", obj.getStr("node_type"));
                node.putByPath("notes",obj.getStr("notes"));
                node.putByPath("parent_id",obj.getStr("parent_id"));
                String branchId = obj.getStr("branch_id");
                String nodeType = obj.getStr("node_type");//1测试用例2流程步8分支 4 流程
                if("2".equals(nodeType)) {
                    //有分支信息的是流程项
                    List<JSONObject> steps = stepMap.get(branchId);
                    if(steps == null) {
                        steps = new ArrayList<>();
                    }
                    steps.add(node);
                    stepMap.put(branchId, steps);
                } else if("8".equals(nodeType)){
                    branchs.add(node);
                } else {

                }
            }
            //分支排序
            branchs = sortStep(branchs,nodeId);
            for(int i = 0;i <branchs.size() ;i++) {
                JSONObject branch = branchs.get(i);
                List<JSONObject> children = stepMap.get(branch.getStr("id"));

                if(children == null) {
                    children = new ArrayList<>();
                } else {
                    //流程步排序
                    children = sortStep(children,branch.getStr("id"));
                }
                branch.putByPath("children", children);
            }
            return ResultMsg.success(branchs);
        }

    }
    private List<JSONObject> sortStep(List<JSONObject> list,String branchId) {
        Map<String,JSONObject> map=new HashMap<String,JSONObject>();
        for(int i = 0; i < list.size(); i++){
            map.put(list.get(i).getStr("parent_id"),list.get(i));
        }
        List<JSONObject>  result=new ArrayList<JSONObject>();
        sortStepMap(result, branchId, map);
        return result;
    }
    private void sortStepMap(List<JSONObject>  result, String parentId,Map<String,JSONObject> nodeMap) {
        JSONObject node = nodeMap.get(parentId);
        if(node != null) {
            result.add(node);
            sortStepMap(result, node.getStr("id"),nodeMap);
        }

    }


    @PostMapping("/line")
    @ApiOperation("连线接口")
    public ResultMsg line(@RequestBody JSONObject param) {
        String type = param.getStr("type");

        String sourceNodeId = param.getStr("sourceNodeId");
        String targetNodeId = param.getStr("targetNodeId");
        String branchOrInstanceId = param.getStr("branchOrInstanceId");//用例或者流程ID
        String content = param.getStr("content");
        //:1、用例2、分支3、流程
        if("2".equals(type)) {

        } else if("1".equals(type)) {

        } else if("3".equals(type)) {

        }
        this.sqlExtService.execute("update c_base_info set parent_id = '"+sourceNodeId+"' where id = '"+targetNodeId+"'");
        this.updateContent(branchOrInstanceId, content);
        return ResultMsg.success();
    }
    @PostMapping("/delLine")
    @ApiOperation("连线接口")
    public ResultMsg delLine(@RequestBody JSONObject param) {
        String sourceNodeId = param.getStr("sourceNodeId");
        String targetNodeId = param.getStr("targetNodeId");
        this.sqlExtService.execute("update c_base_info set parent_id = '"+sourceNodeId+"' where id = '"+targetNodeId+"'");
        String branchOrInstanceId = param.getStr("branchOrInstanceId");//用例或者流程ID
        String content = param.getStr("content");
        this.updateContent(branchOrInstanceId, content);
        return ResultMsg.success();
    }
    @PostMapping("/sortNode")
    @ApiOperation("节点排序")
    public ResultMsg sortNode(@RequestBody JSONObject param) throws Exception {
        String parentId = param.getStr("parentId");
        JSONArray nodes = param.getJSONArray("nodeIds");
        String branchOrInstanceId=param.getStr("branchOrInstanceId");
        String type=param.getStr("type");
        if(parentId != null) {
            if("3".equals(type)&&parentId.equals(branchOrInstanceId)){
                if(nodes!=null&&nodes.size()>0){
                    for(int i=0;i<nodes.size();i++) {
                        String nodeId = nodes.getStr(i);
                        String updatedNodeId ="UPDATE c_base_info SET num='"+i+"' where id='"+nodeId+"'";
                        this.sqlExtService.execute(updatedNodeId);
                        //更新当前用例下所有的节点的分支节点
//                        this.sqlExtService.execute("UPDATE c_base_info SET instance_num='"+i+"' where parent_all_id like '%"+nodeId+"%'");
                    }
                }
            }

        }
//        if(!parentId.equals("1")) {
//            throw new Exception();
//        }
        String content = param.getStr("content");
        this.updateContent(branchOrInstanceId, content);
        return ResultMsg.success();
    }
//    @GetMapping("/getParentNodeAttr")
//    @ApiOperation("获取当前分支的上级节点属性")
//    public ResultMsg getParentNodeAttr(@RequestParam(required = false)  @ApiParam(value = "上级节点", name = "nodeId") String nodeId) {
//        JSONObject node = this.sqlExtService.findOneObject("select * from c_base_info where  id = '"+nodeId+"'", JSONObject.class);
////        List<JSONObject> baseInfos = this.sqlExtService.findListObject("select id,name,parent_id from c_base_info where branch_id = (select ci.branch_id from c_base_info ci where ci.id ='"+nodeId+"')",JSONObject.class);
////        List<JSONObject> baseInfoAttrs = this.sqlExtService.findListObject("select * from c_base_info_attr bia where bia.is_quote = '1' and bia.base_info_id in (" +
////                "select id from c_base_info  where branch_id = (select ci.branch_id from c_base_info ci where ci.id ='"+nodeId+"')" +
////                ")",JSONObject.class);
//        String flowinstance_id = node.getStr("flowinstance_id");
//        List<JSONObject> baseInfos = this.sqlExtService.findListObject("select id,name,parent_id from c_base_info where flowinstance_id = '"+ flowinstance_id+"'",JSONObject.class);
//        List<JSONObject> baseInfoAttrs = this.sqlExtService.findListObject("select * from c_base_info_attr bia where bia.is_quote = '1' and bia.base_info_id in (" +
//                "select id from c_base_info  where flowinstance_id = '"+flowinstance_id+"'" +
//                ")",JSONObject.class);
//        Map<String,JSONObject> map = new HashMap<>();
//        List<JSONObject> currentNodes = new ArrayList<>();
//        for(int i = 0;i < baseInfos.size(); i++) {
//            JSONObject baseInfo = baseInfos.get(i);
//            map.put(baseInfo.getStr("id"), baseInfo);
//            if(nodeId.equals(baseInfo.getStr("id"))) {
//                currentNodes.add(baseInfo);
//            }
//        }
//
//        Map<String, List<JSONObject>> baseInfoAttrMap = CollStreamUtil.groupBy(baseInfoAttrs, item -> (String) item.getStr("base_info_id"), Collectors.toList());
//
//        JSONObject currentNode = currentNodes.get(0);
//        //获取所有节点ID
//        List<String> allIds = new ArrayList<>();
//        findParent(nodeId, map, allIds);
//        Collections.reverse(allIds);
//        List<JSONObject> result = new ArrayList<>();
//        for(int i = 0;i < allIds.size(); i++) {
//            if(nodeId.equals(allIds.get(i))) {
//                continue;
//            }
//            JSONObject obj = map.get(allIds.get(i));
//            String base_info_id = obj.getStr("id");
//            List<JSONObject> children = baseInfoAttrMap.get(base_info_id);
//            if(children != null) {
//                obj.putByPath("children", children);
//                result.add(obj);
//            }
//        }
//            return ResultMsg.success(result);
//    }
@GetMapping("/getParentNodeAttr")
@ApiOperation("获取当前分支的上级节点属性")
public ResultMsg getParentNodeAttr(@RequestParam(required = false)  @ApiParam(value = "上级节点", name = "nodeId") String nodeId) {
    JSONObject node = this.sqlExtService.findOneObject("select * from c_base_info where  id = '"+nodeId+"'", JSONObject.class);
    String type = node.getStr("type");
    List<JSONObject> result = new ArrayList<>();
    //当前画布类型:1、用例2、分支3、流程
    if("3".equals(type)) {
        flowNodeAttr(result, node, nodeId);
    } else if("1".equals(type)) {
        instanceNodeAttr(result, node, nodeId);
    } else if("2".equals(type)) {
        branchNodeAttr(result, node, nodeId);
    }
    return ResultMsg.success(result);
}
private  void flowNodeAttr(List<JSONObject> result,JSONObject node,String nodeId) {
    String flowinstance_id = node.getStr("flowinstance_id");
    List<JSONObject> baseInfos = this.sqlExtService.findListObject("select id,name,parent_id,instance_id,flowinstance_id,branch_id from c_base_info where flowinstance_id = '"+ flowinstance_id+"'",JSONObject.class);
    List<JSONObject> baseInfoAttrs = this.sqlExtService.findListObject("select * from c_base_info_attr bia where bia.is_quote = '1'  and bia.base_info_id in (" +
            "select id from c_base_info  where flowinstance_id = '"+flowinstance_id+"'" +
            ")",JSONObject.class);
    Map<String,JSONObject> baseInfoMap = new HashMap<>();
    List<JSONObject> currentNodes = new ArrayList<>();
    for(int i = 0;i < baseInfos.size(); i++) {
        JSONObject baseInfo = baseInfos.get(i);
//        if(!nodeId.equals(baseInfo.getStr("id"))) {
            baseInfoMap.put(baseInfo.getStr("id"), baseInfo);
//        }
    }

    if(baseInfoAttrs!=null && baseInfoAttrs.size() > 0) {
        for(JSONObject baseInfoAttr : baseInfoAttrs) {
            JSONObject baseInfo = baseInfoMap.get(baseInfoAttr.getStr("base_info_id"));
            if(baseInfo != null) {
                baseInfoAttr.putByPath("instance_id", baseInfo.getStr("instance_id"));
                baseInfoAttr.putByPath("branch_id", baseInfo.getStr("branch_id"));
                baseInfoAttr.putByPath("node_id", baseInfo.getStr("id"));
                baseInfoAttr.putByPath("instance_name", baseInfoMap.get(baseInfo.getStr("instance_id")).getStr("name"));
                baseInfoAttr.putByPath("branch_name", baseInfoMap.get(baseInfo.getStr("branch_id")).getStr("name"));
                baseInfoAttr.putByPath("node_name", baseInfo.getStr("name"));
                result.add(baseInfoAttr);
            }
        }
    }
}
    private  void instanceNodeAttr(List<JSONObject> result,JSONObject node,String nodeId) {
        String instance_id = node.getStr("instance_id");
        List<JSONObject> baseInfos = this.sqlExtService.findListObject("select id,name,parent_id,instance_id,flowinstance_id,branch_id from c_base_info where instance_id = '"+ instance_id+"'",JSONObject.class);
        List<JSONObject> baseInfoAttrs = this.sqlExtService.findListObject("select * from c_base_info_attr bia where bia.is_quote = '1'   and bia.base_info_id in (" +
                "select id from c_base_info  where instance_id = '"+instance_id+"'" +
                ")",JSONObject.class);
        Map<String,JSONObject> baseInfoMap = new HashMap<>();
        List<JSONObject> currentNodes = new ArrayList<>();
        for(int i = 0;i < baseInfos.size(); i++) {
            JSONObject baseInfo = baseInfos.get(i);
//            if(!nodeId.equals(baseInfo.getStr("id"))) {
                baseInfoMap.put(baseInfo.getStr("id"), baseInfo);
//            }
        }

        if(baseInfoAttrs!=null && baseInfoAttrs.size() > 0) {
            for(JSONObject baseInfoAttr : baseInfoAttrs) {
                JSONObject baseInfo = baseInfoMap.get(baseInfoAttr.getStr("base_info_id"));
                if(baseInfo != null) {
                    //                baseInfoAttr.putByPath("instance_id", baseInfo.getStr("instance_id"));
                    baseInfoAttr.putByPath("branch_id", baseInfo.getStr("branch_id"));
                    baseInfoAttr.putByPath("node_id", baseInfo.getStr("id"));
//                baseInfoAttr.putByPath("instance_name", baseInfoMap.get(baseInfo.getStr("instance_id")).getStr("name"));
                    baseInfoAttr.putByPath("branch_name", baseInfoMap.get(baseInfo.getStr("branch_id")).getStr("name"));
                    baseInfoAttr.putByPath("node_name", baseInfo.getStr("name"));
                    result.add(baseInfoAttr);
                }
            }
        }
    }

    private  void branchNodeAttr(List<JSONObject> result,JSONObject node,String nodeId) {
        String branch_id = node.getStr("branch_id");
        List<JSONObject> baseInfos = this.sqlExtService.findListObject("select id,name,parent_id,instance_id,flowinstance_id,branch_id from c_base_info where branch_id = '"+ branch_id+"'",JSONObject.class);
        String sql = "select * from c_base_info_attr bia where bia.is_quote = '1' and  bia.base_info_id in (" +
                "select id from c_base_info  where branch_id = '"+branch_id+"'" +
                ")";
        List<JSONObject> baseInfoAttrs = this.sqlExtService.findListObject(sql,JSONObject.class);
        Map<String,JSONObject> baseInfoMap = new HashMap<>();
        List<JSONObject> currentNodes = new ArrayList<>();
        for(int i = 0;i < baseInfos.size(); i++) {
            JSONObject baseInfo = baseInfos.get(i);
//            if(!branch_id.equals(baseInfo.getStr("id"))) {
                baseInfoMap.put(baseInfo.getStr("id"), baseInfo);
//            }
        }

        if(baseInfoAttrs!=null && baseInfoAttrs.size() > 0) {
            for(JSONObject baseInfoAttr : baseInfoAttrs) {
                JSONObject baseInfo = baseInfoMap.get(baseInfoAttr.getStr("base_info_id"));
                if(baseInfo != null) {
                    baseInfoAttr.putByPath("node_id", baseInfo.getStr("id"));
                    baseInfoAttr.putByPath("node_name", baseInfo.getStr("name"));
                    result.add(baseInfoAttr);
                }
            }
        }
    }
    private void findParent(String nodeId,Map<String,JSONObject> map,List<String> ids) {
        JSONObject obj = map.get(nodeId);
        if(obj != null) {
            ids.add(obj.getStr("id"));
            String parentId = obj.getStr("parent_id");
            if(StringUtils.isNotBlank(parentId)) {
                findParent(parentId,map, ids);
            }
        }
    }

    private void updateContent(String id, String content) {
        Map<String,Object> obj = new HashMap<>();
        obj.put("id",id);
        obj.put("content",content);
        //c_project_flow_instance 更新测试用例表
        sqlService.execute("3",obj);
    }

    @PostMapping("/updateContentById")
    @ApiOperation("第一次更新画布")
    public ResultMsg updateContentById(@RequestBody JSONObject param) {
        //批量保存数据
        String branchOrInstanceId = param.getStr("branchOrInstanceId");//用例或者流程ID或者分支ID
        String content = param.getStr("content");
        this.updateContent(branchOrInstanceId, content);
        return ResultMsg.success();
    }


    /**
     * 项目生成XML
     * @param param
     * @return
     */
    @PostMapping("/exportProject")
    @ApiOperation("项目生成XML")
    public ResultMsg exportProject(@RequestBody JSONObject param) {
        String projectId = param.getStr("projectId");
        try{
            JSONObject project = this.sqlExtService.findOneObject("select * from c_project where id = '"+projectId+"'", JSONObject.class);
            String projectName = project.getStr("project_name");
            String projectPath = project.getStr("project_path");
            if(StringUtils.isBlank(projectPath)) {
                return ResultMsg.fail("请填写项目路径!");
            }

            //创建项目目录
            String dirPath = projectPath + File.separator + projectName;
            File directory = new File(dirPath);
            if (!directory.exists()) {
                if (!directory.mkdirs()) {
                    return ResultMsg.fail(String.format("创建目录%s失败", dirPath));
                }
            }
            //生成总的XML
            xmlProjectService.createProjectXml(project);
            //生成硬件协议
            xmlHardConfigService.createHardConfig(project);
            //生成总线协议
            xmlBusConfigService.createBusConfigXML(project);
            //生成观察者
            xmlObserverConfigService.createObserverConfigXml(project);
            //生成协议配置
            xmlProtocolConfigService.createProtocolConfigXml(project);
            //生成共享配置
            xmlShareConfigService.createShareConfigXml(project);
            //生成流程文件
            List<JSONObject> flows = this.sqlExtService.findListObject("select id,name from c_project_attr where project_id = '"+projectId+"' and config_type = '6' order by create_time asc", JSONObject.class);
            List<JSONObject> projectConfigs = this.sqlExtService.findListObject("select id,config_code from c_project_config", JSONObject.class);
            Map<String,String> projectConfigMap = new HashMap<>();
            if(projectConfigs != null &&  projectConfigs.size() > 0) {
                for (JSONObject projectConfig:projectConfigs) {
                    projectConfigMap.put(projectConfig.getStr("id"), projectConfig.getStr("config_code"));
                }
            }
            for(JSONObject flow:flows) {
                xmlFlowConfigService.init();
                xmlFlowConfigService.createFlowTestConfigXml(project, flow,projectConfigMap);
            }
        }catch (Exception e) {
            e.printStackTrace();
            return ResultMsg.fail("生成XML失败"+e.getMessage());
        }
        return ResultMsg.success("XML生成成功");
    }

    @PostMapping(value = "/importFlow")
    @ApiOperation(value = "导入流程")
    public ResultMsg importFlow(@RequestParam @ApiParam(value = "文件", name = "file") MultipartFile file,
                                @Param("projecId") String projectId) {
        //导入返回的数据
        JSONObject resultObj = JSONUtil.createObj();
        File saveFile = FileUtil.newFile(FileUtil.getTmpDir()+File.separator+IdUtil.getSnowflakeNextIdStr() + ".txt");
        try {
            InputStream inputStream = file.getInputStream();

            FileOutputStream fos = new FileOutputStream(saveFile);
            byte[] buffer = new byte[1024];
            int len = 0;
            while ((len = inputStream.read(buffer)) != -1) {
                fos.write(buffer, 0, len);
            }
            fos.close();
            String infos = FileUtil.readUtf8String(saveFile);
            JSONObject result = JSONUtil.parseObj(infos);
            JSONArray baseInfos = result.getJSONArray("baseInfos");
            JSONArray baseInfoAttrs = result.getJSONArray("baseInfoAttrs");



            //旧ID 与 新 ID 的映射关联关系
            Map<String,String> idMap = new HashMap<>();
            JSONObject baseInfo = null;
            JSONObject baseInfoAttr = null;
            //生成所有的ID
            for(int i = 0;i < baseInfos.size(); i++) {
                baseInfo = baseInfos.getJSONObject(i);
                idMap.put(baseInfo.getStr("id"), IdUtil.getSnowflakeNextIdStr());
            }
            //提供默认值
            idMap.put("","");

            List<JSONObject> baseInfoList = new ArrayList<>();
            List<JSONObject> baseInfoAttrList = new ArrayList<>();
            JSONObject projectFlowInstance = result.getJSONObject("projectFlowInstance");
            String projectFlowInstanceId = null;

            for(int i = 0;i < baseInfos.size(); i++) {
                baseInfo = baseInfos.getJSONObject(i);
                String branch_id = idMap.get(baseInfo.getStr("branch_id",""));
                String instance_id = idMap.get(baseInfo.getStr("instance_id",""));
                String flowinstance_id = idMap.get(baseInfo.getStr("flowinstance_id",""));
                baseInfo.putByPath("id", idMap.get(baseInfo.getStr("id","")));
                baseInfo.putByPath("parent_id", idMap.get(baseInfo.getStr("parent_id","")));
                baseInfo.putByPath("instance_id", instance_id);
                baseInfo.putByPath("flowinstance_id", flowinstance_id);
                baseInfo.putByPath("branch_id", branch_id);
                baseInfo.putByPath("project_id", projectId);
                String node_type = baseInfo.getStr("node_type");
                baseInfo.putByPath("create_user", UserLoginUtils.getCurrentUser() == null ? "admin" : UserLoginUtils.getCurrentUser().getId().toString());
                baseInfo.putByPath("create_time", DateUtils.getDateTimeStr());
                if("2".equals(node_type)) {
                    //流程步
                    baseInfo.putByPath("parent_all_id", branch_id + "|" +instance_id + "|" +flowinstance_id);
                } else if("8".equals(node_type)) {
                    //分支
                    baseInfo.putByPath("parent_all_id", branch_id + "|" +instance_id + "|" +flowinstance_id);
                } else if("1".equals(node_type)) {
                    //测试用例
                    baseInfo.putByPath("parent_all_id", instance_id + "|" +flowinstance_id);
                } else if("4".equals(node_type)) {
                    //流程
                    baseInfo.putByPath("parent_all_id", flowinstance_id);

                    resultObj.putByPath("id", baseInfo.getStr("id"));
                    resultObj.putByPath("name", baseInfo.getStr("name"));
                    resultObj.putByPath("create_time", baseInfo.getStr("create_time"));
                    resultObj.putByPath("project_id", projectId);
                    resultObj.putByPath("config_type", "6");

                    projectFlowInstance.putByPath("id", baseInfo.getStr("id",""));
                    projectFlowInstanceId = baseInfo.getStr("id","");
                    projectFlowInstance.putByPath("create_time", baseInfo.getStr("create_time",""));
                }

                baseInfoList.add(baseInfo);
            }

            //构建属性数据
            for(int i = 0;i < baseInfoAttrs.size(); i++) {
                baseInfoAttr = baseInfoAttrs.getJSONObject(i);
                baseInfoAttr.putByPath("id", IdUtil.getSnowflakeNextIdStr());
                baseInfoAttr.putByPath("base_info_id", idMap.get(baseInfoAttr.getStr("baseInfoAttr")));
                baseInfoAttr.putByPath("create_user", UserLoginUtils.getCurrentUser() == null ? "admin" : UserLoginUtils.getCurrentUser().getId().toString());
                baseInfoAttr.putByPath("create_time", DateUtils.getDateTimeStr());
                baseInfoAttrList.add(baseInfoAttr);
            }

            //生成流程画布数据
            if(StringUtils.isBlank(projectFlowInstanceId)) {
                //当不存在数据的情况生成ID
                projectFlowInstance.putByPath("id", IdUtil.getSnowflakeNextIdStr());
                projectFlowInstance.putByPath("create_time", DateUtils.getDateTimeStr());
            }
            Map<String, Object> paramFlow = JSONUtil.toBean(projectFlowInstance.toString(), Map.class);
            sqlService.execute("10",paramFlow);

            //批量保存数据
            Map<String,Object> paramMap = new HashMap<>();

            //保存base_info数据
            paramMap.put("list", baseInfoList);
            this.sqlService.execute("9", paramMap);

            //保存 c_base_info_attr 数据
            paramMap.put("list", baseInfoAttrList);

            this.sqlService.execute("7", paramMap);
        } catch (Exception e) {
            e.printStackTrace();
            ResultMsg.fail("导入失败,请联系管理员");
        } finally {
            saveFile.deleteOnExit();
        }
        return ResultMsg.success(resultObj);
    }

//    @GetMapping(value = "/exportFlow")
//    @ApiOperation(value = "导出流程")
//    public void exportFlow(String flowId,String projectId,
//                           HttpServletResponse response) {
//        //查询用例名称
//        String flowName = this.sqlExtService.findOne("select name from c_base_info where id = '"+flowId+"'", String.class);
//        List<JSONObject> baseInfos = this.sqlExtService.findListObject("select * from c_base_info where  parent_all_id like '%"+flowId+"%'  order by num desc", JSONObject.class);
//        List<JSONObject> baseInfoAttrs =  this.sqlExtService.findListObject("select * from c_base_info_attr where base_info_id in (select bi.id from c_base_info bi where  bi.parent_all_id like '%"+flowId+"%')", JSONObject.class);
//        JSONObject result = JSONUtil.createObj();
//        JSONObject projectFlowInstance = this.sqlExtService.findOneObject("select * from c_project_flow_instance where  id = '"+flowId+"'", JSONObject.class);
//        result.putByPath("projectFlowInstance",projectFlowInstance);
//        result.putByPath("baseInfos",baseInfos);
//        result.putByPath("baseInfoAttrs",baseInfoAttrs);
//        File file = FileUtil.newFile(FileUtil.getTmpDir()+File.separator+IdUtil.getSnowflakeNextIdStr() + ".txt");
//
//        FileUtil.writeUtf8String(result.toString(),file);
//        try {
//            flowName = flowName + ".txt";
//            response.setHeader("Content-Disposition", "attachment;Filename=" + URLEncoder.encode(flowName, "UTF-8"));
//            response.setHeader("Content-Type", "application/octet-stream");
//            OutputStream os = response.getOutputStream();
//            byte[] b = new byte[100];
//            int len;
//            FileInputStream fileInputStream = new FileInputStream(file);
//            while ((len = fileInputStream.read(b)) > 0) {
//                os.write(b, 0, len);
//            }
//            fileInputStream.close();
//        } catch (Exception e) {
//            e.printStackTrace();
//        } finally {
//            file.deleteOnExit();
//        }
//    }
//
//
    @PostMapping(value = "/importInstance")
    @ApiOperation(value = "导入用例")
    public ResultMsg importInstance(@RequestParam @ApiParam(value = "文件", name = "file") MultipartFile file) {
        File saveFile = FileUtil.newFile(FileUtil.getTmpDir()+File.separator+IdUtil.getSnowflakeNextIdStr() + ".txt");
        try {
            InputStream inputStream = file.getInputStream();

            FileOutputStream fos = new FileOutputStream(saveFile);
            byte[] buffer = new byte[1024];
            int len = 0;
            while ((len = inputStream.read(buffer)) != -1) {
                fos.write(buffer, 0, len);
            }
            fos.close();
            String infos = FileUtil.readUtf8String(saveFile);
            if(infos.startsWith("[")) {
               JSONArray ja = JSONUtil.parseArray(infos);
               for(int i = 0; i < ja.size(); i++) {
                   JSONObject result = ja.getJSONObject(i);
                   importDate(result);
               }
            } else {
                JSONObject result = JSONUtil.parseObj(infos);
                importDate(result);
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            saveFile.deleteOnExit();
        }
        return ResultMsg.success();
    }
    private void importDate(JSONObject result) {
        JSONArray baseInfos = result.getJSONArray("baseInfos");
        JSONArray baseInfoAttrs = result.getJSONArray("baseInfoAttrs");
        JSONObject projectFlowInstance = result.getJSONObject("projectFlowInstance");
        JSONObject yw = result.getJSONObject("yw");
        String projectFlowInstanceId = null;
        String ywId = "";
        if(yw != null) {
            ywId = yw.getStr("yw_id");

        }

        //旧ID 与 新 ID 的映射关联关系
        Map<String,String> idMap = new HashMap<>();
        JSONObject baseInfo = null;
        JSONObject baseInfoAttr = null;
        //生成所有的ID
        for(int i = 0;i < baseInfos.size(); i++) {
            baseInfo = baseInfos.getJSONObject(i);
            idMap.put(baseInfo.getStr("id"), IdUtil.getSnowflakeNextIdStr());
        }
        //提供默认值
        idMap.put("","");

        List<JSONObject> baseInfoList = new ArrayList<>();
        List<JSONObject> baseInfoAttrList = new ArrayList<>();
        for(int i = 0;i < baseInfos.size(); i++) {
            baseInfo = baseInfos.getJSONObject(i);
            String branch_id = idMap.get(baseInfo.getStr("branch_id",""));
            String instance_id = idMap.get(baseInfo.getStr("instance_id",""));
            String flowinstance_id = idMap.get(baseInfo.getStr("flowinstance_id",""));
            baseInfo.putByPath("id", idMap.get(baseInfo.getStr("id","")));
            baseInfo.putByPath("parent_id", idMap.get(baseInfo.getStr("parent_id","")));
            baseInfo.putByPath("instance_id", instance_id);
            baseInfo.putByPath("flowinstance_id", flowinstance_id);
            baseInfo.putByPath("branch_id", branch_id);
            baseInfo.putByPath("project_id", "");
            String node_type = baseInfo.getStr("node_type");
            baseInfo.putByPath("create_user", UserLoginUtils.getCurrentUser() == null ? "admin" : UserLoginUtils.getCurrentUser().getId().toString());
            baseInfo.putByPath("create_time", DateUtils.getDateTimeStr());
            if("2".equals(node_type)) {
                //流程步
                baseInfo.putByPath("parent_all_id", branch_id + "|" +instance_id + "|" +flowinstance_id);
            } else if("8".equals(node_type)) {
                //分支
                baseInfo.putByPath("parent_all_id", branch_id + "|" +instance_id + "|" +flowinstance_id);
            } else if("1".equals(node_type)) {
                //测试用例
                baseInfo.putByPath("parent_all_id", instance_id + "|" +flowinstance_id);
                projectFlowInstance.putByPath("id", baseInfo.getStr("id",""));
                projectFlowInstanceId = baseInfo.getStr("id","");
                projectFlowInstance.putByPath("create_time", baseInfo.getStr("create_time",""));
            } else if("4".equals(node_type)) {
                //流程
                baseInfo.putByPath("parent_all_id", flowinstance_id);
            }

            baseInfoList.add(baseInfo);
        }

        //生成用例数据
        if(StringUtils.isBlank(projectFlowInstanceId)) {
            //当不存在数据的情况生成ID
            projectFlowInstance.putByPath("id", IdUtil.getSnowflakeNextIdStr());
            projectFlowInstance.putByPath("create_time", DateUtils.getDateTimeStr());
        }
        Map<String, Object> paramFlow = JSONUtil.toBean(projectFlowInstance.toString(), Map.class);

        sqlService.execute("10",paramFlow);

        //构建属性数据
        for(int i = 0;i < baseInfoAttrs.size(); i++) {
            baseInfoAttr = baseInfoAttrs.getJSONObject(i);
            baseInfoAttr.putByPath("id", IdUtil.getSnowflakeNextIdStr());
            baseInfoAttr.putByPath("base_info_id", idMap.get(baseInfoAttr.getStr("baseInfoAttr")));
            baseInfoAttr.putByPath("create_user", UserLoginUtils.getCurrentUser() == null ? "admin" : UserLoginUtils.getCurrentUser().getId().toString());
            baseInfoAttr.putByPath("create_time", DateUtils.getDateTimeStr());
            replateBaseInfoAttr(baseInfoAttr);
            baseInfoAttrList.add(baseInfoAttr);
        }
        //批量保存数据
        Map<String,Object> paramMap = new HashMap<>();

        //保存base_info数据
        paramMap.put("list", baseInfoList);
        this.sqlService.execute("9", paramMap);

        //保存 c_base_info_attr 数据
        paramMap.put("list", baseInfoAttrList);
        this.sqlService.execute("7", paramMap);

        //用例插入用例业务类型数据
        if(StringUtils.isNotBlank(ywId)) {
            Map<String,Object> ywMap = new HashMap<>();
            String ywId1 = IdUtil.getSnowflakeNextIdStr();
            ywMap.put("id", ywId1);
            ywMap.put("yw_id", ywId);
            ywMap.put("yl_id", projectFlowInstance.getStr("id"));
            this.sqlService.execute("30" , ywMap);
        }

    }
    @PostMapping(value = "/saveOther")
    @ApiOperation(value = "另存为")
    public ResultMsg saveOther(@RequestBody JSONObject param) {

        try {
            String instanceId= param.getStr("instanceId");
            String instanceName = param.getStr("instanceName");
            List<JSONObject> baseInfos = this.sqlExtService.findListObject("select * from c_base_info where  parent_all_id like '%" + instanceId + "%'  order by num desc", JSONObject.class);
            List<JSONObject> baseInfoAttrs = this.sqlExtService.findListObject("select * from c_base_info_attr where base_info_id in (select bi.id from c_base_info bi where  bi.parent_all_id like '%" + instanceId + "%')", JSONObject.class);
            JSONObject projectFlowInstance = this.sqlExtService.findOneObject("select * from c_project_flow_instance where  id in (select c.source_id from c_base_info c where c.id = '"+instanceId+"')", JSONObject.class);
            if(projectFlowInstance == null) {
                projectFlowInstance = JSONUtil.createObj();
                projectFlowInstance.putByPath("type_id", "b9c87a0def034ab9941c7ed98478b980");
                projectFlowInstance.putByPath("bus_type", "2");
            }
            projectFlowInstance.putByPath("instance_name", instanceName == null?"":instanceName);
            String projectFlowInstanceId = null;


            //旧ID 与 新 ID 的映射关联关系
            Map<String,String> idMap = new HashMap<>();
            JSONObject baseInfo = null;
            JSONObject baseInfoAttr = null;
            //生成所有的ID
            String instance_content = projectFlowInstance.getStr("instance_content", "");
            for(int i = 0;i < baseInfos.size(); i++) {
                baseInfo = baseInfos.get(i);
                idMap.put(baseInfo.getStr("id"), IdUtil.getSnowflakeNextIdStr());
                if(StringUtils.isNotBlank(instance_content)) {
                    instance_content = instance_content.replaceAll(baseInfo.getStr("id"), idMap.get(baseInfo.getStr("id")));
                }
            }
            projectFlowInstance.putByPath("instance_content", instance_content);
            //提供默认值
            idMap.put("","");

            List<JSONObject> baseInfoList = new ArrayList<>();
            List<JSONObject> baseInfoAttrList = new ArrayList<>();
            for(int i = 0;i < baseInfos.size(); i++) {
                baseInfo = baseInfos.get(i);
                String branch_id = idMap.get(baseInfo.getStr("branch_id",""));
                String instance_id = idMap.get(baseInfo.getStr("instance_id",""));
                String flowinstance_id = idMap.get(baseInfo.getStr("flowinstance_id",""));
                baseInfo.putByPath("id", idMap.get(baseInfo.getStr("id","")));
                baseInfo.putByPath("parent_id", idMap.get(baseInfo.getStr("parent_id","")));
                baseInfo.putByPath("instance_id", instance_id);
                baseInfo.putByPath("flowinstance_id", flowinstance_id);
                baseInfo.putByPath("branch_id", branch_id);
                baseInfo.putByPath("project_id", "");
                String node_type = baseInfo.getStr("node_type");
                baseInfo.putByPath("create_user", UserLoginUtils.getCurrentUser() == null ? "admin" : UserLoginUtils.getCurrentUser().getId().toString());
                baseInfo.putByPath("create_time", DateUtils.getDateTimeStr());
                if("2".equals(node_type)) {
                    //流程步
                    baseInfo.putByPath("parent_all_id", branch_id + "|" +instance_id + "|" +flowinstance_id);
                } else if("8".equals(node_type)) {
                    //分支
                    baseInfo.putByPath("parent_all_id", branch_id + "|" +instance_id + "|" +flowinstance_id);
                } else if("1".equals(node_type)) {
                    //测试用例
                    baseInfo.putByPath("parent_all_id", instance_id + "|" +flowinstance_id);
                    projectFlowInstance.putByPath("id", baseInfo.getStr("id",""));
                    projectFlowInstanceId = baseInfo.getStr("id","");
                    projectFlowInstance.putByPath("create_time", baseInfo.getStr("create_time",""));
                } else if("4".equals(node_type)) {
                    //流程
                    baseInfo.putByPath("parent_all_id", flowinstance_id);
                }

                baseInfoList.add(baseInfo);
            }

            //生成用例数据
            if(StringUtils.isBlank(projectFlowInstanceId)) {
                //当不存在数据的情况生成ID
                projectFlowInstance.putByPath("id", IdUtil.getSnowflakeNextIdStr());
                projectFlowInstance.putByPath("create_time", DateUtils.getDateTimeStr());
            }
            Map<String, Object> paramFlow = JSONUtil.toBean(projectFlowInstance.toString(), Map.class);

            sqlService.execute("10",paramFlow);

            //构建属性数据
            for(int i = 0;i < baseInfoAttrs.size(); i++) {
                baseInfoAttr = baseInfoAttrs.get(i);
                baseInfoAttr.putByPath("id", IdUtil.getSnowflakeNextIdStr());
                baseInfoAttr.putByPath("base_info_id", idMap.get(baseInfoAttr.getStr("baseInfoAttr")));
                baseInfoAttr.putByPath("create_user", UserLoginUtils.getCurrentUser() == null ? "admin" : UserLoginUtils.getCurrentUser().getId().toString());
                baseInfoAttr.putByPath("create_time", DateUtils.getDateTimeStr());
                replateBaseInfoAttr(baseInfoAttr);
                baseInfoAttrList.add(baseInfoAttr);
            }
            //批量保存数据
            Map<String,Object> paramMap = new HashMap<>();

            //保存base_info数据
            paramMap.put("list", baseInfoList);
            this.sqlService.execute("9", paramMap);

            //保存 c_base_info_attr 数据
            paramMap.put("list", baseInfoAttrList);
            this.sqlService.execute("7", paramMap);
        } catch (Exception e) {
            e.printStackTrace();
        } finally {

        }
        return ResultMsg.success();
    }
//    @GetMapping(value = "/exportInstance")
//    @ApiOperation(value = "导出用例")
//    public void exportInstance(@RequestParam @ApiParam(value = "用例ID", name = "instanceId") String instanceId,
//                               HttpServletResponse response) {
//        //查询用例名称
//        String instanceName = this.sqlExtService.findOne("select name from c_base_info where id = '"+instanceId+"'", String.class);
//        List<JSONObject> baseInfos = this.sqlExtService.findListObject("select * from c_base_info where  parent_all_id like '%"+instanceId+"%'  order by num desc", JSONObject.class);
//        List<JSONObject> baseInfoAttrs =  this.sqlExtService.findListObject("select * from c_base_info_attr where base_info_id in (select bi.id from c_base_info bi where  bi.parent_all_id like '%"+instanceId+"%')", JSONObject.class);
//        JSONObject result = JSONUtil.createObj();
//        JSONObject projectFlowInstance = this.sqlExtService.findOneObject("select * from c_project_flow_instance where  id = '"+instanceId+"'", JSONObject.class);
//        result.putByPath("projectFlowInstance",projectFlowInstance);
//        result.putByPath("baseInfos",baseInfos);
//        result.putByPath("baseInfoAttrs",baseInfoAttrs);
//        File file = FileUtil.newFile(FileUtil.getTmpDir()+File.separator+IdUtil.getSnowflakeNextIdStr() + ".txt");
//
//        FileUtil.writeUtf8String(result.toString(),file);
//        try {
//            instanceName = instanceName + ".txt";
//            response.setHeader("Content-Disposition", "attachment;Filename=" + URLEncoder.encode(instanceName, "UTF-8"));
//            response.setHeader("Content-Type", "application/octet-stream");
//            OutputStream os = response.getOutputStream();
//            byte[] b = new byte[100];
//            int len;
//            FileInputStream fileInputStream = new FileInputStream(file);
//            while ((len = fileInputStream.read(b)) > 0) {
//                os.write(b, 0, len);
//            }
//            fileInputStream.close();
//        } catch (Exception e) {
//            e.printStackTrace();
//        } finally {
//            file.deleteOnExit();
//        }
//    }




    @GetMapping("/deleteTemplateInfo")
    @ApiOperation("删除模版")
    public ResultMsg deleteTemplateInfo(@RequestParam @ApiParam(value = "模版ID", name = "id") String id) {
        try{
            this.sqlExtService.execute("delete from c_template where id = '"+id+"'");
            this.sqlExtService.execute("delete from c_template_attr where template_id = '"+id+"'");
            //删除关联表
            sqlExtService.execute("delete from c_type_rel where transaction_id = '"+id+"'");
        }catch (Exception e) {
            e.printStackTrace();
            ResultMsg.fail("服务端异常!");
        }

        return ResultMsg.success();
    }
    @PostMapping("/validateNode")
    @ApiOperation("验证分支")
    public ResultMsg validateNode(@RequestBody JSONObject param) {
        String branchId = param.getStr("branchId");
        List<String> list = new ArrayList<>();
        //结束节点ID
        String end = "5bd46e9e082491f3912571100fa8e051";
        list.add("bf818b5acbe110df5adfd674c1f4199e");
        list.add("78e87569519f28d70e0c50398e75072a");
        list.add("13c47a338f45fd2cb8ab483b13555ca6");
        int beginNum = 0;
        int endNum = 0;
        List<JSONObject> nodes = sqlExtService.findListObject("select * from c_base_info where parent_all_id like '%"+branchId+"%' and node_type = '2'", JSONObject.class);
        if(nodes != null) {
            for(JSONObject node: nodes) {
                String template_id = node.getStr("template_id");
                if (end.equals(template_id)) {
                    endNum = endNum + 1;
                }
                if (list.contains(template_id)) {
                    beginNum = beginNum + 1;
                }
            }
        }
        if (beginNum != endNum) {
            ResultMsg.fail("有未结束判断节点！");
        }


        return ResultMsg.success("验证通过！");
    }

    @PostMapping(value = "/exportFlow")
    @ApiOperation(value = "导出流程")
    public ResultMsg exportFlow(@RequestBody JSONObject param) {
        String flowId= param.getStr("flowId");
        String projectId=param.getStr("projectId");
        String exportPath= param.getStr("exportPath");
        //查询用例名称
        try {
            String flowName = this.sqlExtService.findOne("select name from c_base_info where id = '"+flowId+"'", String.class);
            List<JSONObject> baseInfos = this.sqlExtService.findListObject("select * from c_base_info where  parent_all_id like '%"+flowId+"%'  order by num desc", JSONObject.class);
            List<JSONObject> baseInfoAttrs =  this.sqlExtService.findListObject("select * from c_base_info_attr where base_info_id in (select bi.id from c_base_info bi where  bi.parent_all_id like '%"+flowId+"%')", JSONObject.class);
            JSONObject result = JSONUtil.createObj();
            JSONObject projectFlowInstance = this.sqlExtService.findOneObject("select * from c_project_flow_instance where  id = '"+flowId+"'", JSONObject.class);
            result.putByPath("projectFlowInstance",projectFlowInstance);
            result.putByPath("baseInfos",baseInfos);
            result.putByPath("baseInfoAttrs",baseInfoAttrs);
//            File file = FileUtil.newFile(exportPath+File.separator+IdUtil.getSnowflakeNextIdStr() + ".txt");
            File file = FileUtil.newFile(exportPath+File.separator+projectFlowInstance.get("instance_name") + ".txt");

            FileUtil.writeUtf8String(result.toString(),file);
        }catch (Exception e){
            return  ResultMsg.fail("流程导出失败");
        }
        return  ResultMsg.success("流程导出成功");
    }
    @PostMapping(value = "/exportInstance")
    @ApiOperation(value = "导出用例")
    public ResultMsg exportInstance(@RequestBody JSONObject param){
        String instanceId= param.getStr("instanceId");
        String exportPath=param.getStr("exportPath");
        String instanceIds= param.getStr("instanceIds");
        //查询用例名称
        try {
            String name = "";
            if(StringUtils.isNotBlank(instanceIds)) {
                JSONArray instanceIdArray = JSONUtil.parseArray(instanceIds);
                JSONArray ja = JSONUtil.createArray();
                for(int i = 0;i < instanceIdArray.size(); i++) {
                    instanceId = instanceIdArray.getStr(i);
                    String instanceName = this.sqlExtService.findOne("select name from c_base_info where id = '" + instanceId + "'", String.class);
                    if(i == 0) {
                        name = instanceName;
                    }
                    List<JSONObject> baseInfos = this.sqlExtService.findListObject("select * from c_base_info where  parent_all_id like '%" + instanceId + "%' or id = '"+instanceId+"'  order by num desc", JSONObject.class);
                    List<JSONObject> baseInfoAttrs = this.sqlExtService.findListObject("select * from c_base_info_attr where base_info_id in (select bi.id from c_base_info bi where  bi.parent_all_id like '%" + instanceId + "%' or bi.id = '"+instanceId+"')", JSONObject.class);
                    JSONObject result = JSONUtil.createObj();
                    JSONObject projectFlowInstance = this.sqlExtService.findOneObject("select * from c_project_flow_instance where  id = '" + instanceId + "'", JSONObject.class);
                    result.putByPath("projectFlowInstance", projectFlowInstance);
                    //导出业务属性
                    JSONObject yw = this.sqlExtService.findOneObject("select * from c_yw where yl_id = '"+instanceId+"'", JSONObject.class);
                    if(yw == null) {
                        yw = JSONUtil.createObj();
                    }
                    result.putByPath("yw", yw);
                    result.putByPath("baseInfos", baseInfos);
                    result.putByPath("baseInfoAttrs", baseInfoAttrs);
                    ja.add(result);
                }
//            File file = FileUtil.newFile(exportPath + File.separator + IdUtil.getSnowflakeNextIdStr() + ".txt");
                File file = FileUtil.newFile(exportPath + File.separator + name+ ".txt");
                FileUtil.writeUtf8String(ja.toString(), file);
            } else {
                String instanceName = this.sqlExtService.findOne("select name from c_base_info where id = '" + instanceId + "'", String.class);
                List<JSONObject> baseInfos = this.sqlExtService.findListObject("select * from c_base_info where  parent_all_id like '%" + instanceId + "%'  order by num desc", JSONObject.class);
                List<JSONObject> baseInfoAttrs = this.sqlExtService.findListObject("select * from c_base_info_attr where base_info_id in (select bi.id from c_base_info bi where  bi.parent_all_id like '%" + instanceId + "%')", JSONObject.class);
                JSONObject result = JSONUtil.createObj();
                JSONObject projectFlowInstance = this.sqlExtService.findOneObject("select * from c_project_flow_instance where  id = '" + instanceId + "'", JSONObject.class);
                JSONObject yw = this.sqlExtService.findOneObject("select * from c_yw where yl_id = '"+instanceId+"'", JSONObject.class);
                if(yw == null) {
                    yw = JSONUtil.createObj();
                }
                result.putByPath("yw", yw);
                result.putByPath("projectFlowInstance", projectFlowInstance);
                result.putByPath("baseInfos", baseInfos);
                result.putByPath("baseInfoAttrs", baseInfoAttrs);
//            File file = FileUtil.newFile(exportPath + File.separator + IdUtil.getSnowflakeNextIdStr() + ".txt");
                File file = FileUtil.newFile(exportPath + File.separator + projectFlowInstance.get("instance_name")+ ".txt");

                FileUtil.writeUtf8String(result.toString(), file);
            }

        }catch (Exception e){
            e.printStackTrace();
            return ResultMsg.fail("用例导出失败");
        }
        return ResultMsg.success("用例导出成功");

    }


    @PostMapping(value = "/userAuth")
    @ApiOperation(value = "用户权限")
    public ResultMsg userAuth(@RequestBody JSONObject param){
        String userId= param.getStr("userId");
        List<String> list = new ArrayList<>();
//        for(int i = 1;i < 55; i++) {
//            list.add(i+"");
//        }
        List<String> menuCodes = this.sqlExtService.findList("select menu_code from sys_user_menu where user_id = '"+userId+"'", String.class);
        if(menuCodes != null) {
            list.addAll(menuCodes);
        }
        return ResultMsg.success(list);

    }

    @GetMapping("/nodeTemplateDetailAttrList")
    @ApiOperation("节点模板详情与属性列表查询")
    public ResultMsg<List<JSONObject>> nodeTemplateDetailAttrList(@RequestParam(value = "nodeId") String nodeId) {

        return templateService.nodeTemplateDetailAttrList(nodeId);
    }

    @PostMapping("/baseInfoAttrSaveUpdate")
    @ApiOperation("模板详情与属性列表保存修改")
    //@RequestAuth(poicy = AuthPoicy.AUTH)
    public ResultMsg baseInfoAttrSaveUpdate(@RequestBody BaseInfoAttrListOrder order) {

        return templateService.baseInfoAttrSaveUpdate(order);
    }

}
